#include "ReaderThread.h"
#include "McuRPCManager.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <log/log.h>

namespace android {

ReaderThread::ReaderThread(McuRPCManager* manager, int hw_type, BufferQueue<McuRPCBuffer>* queue)
{
    mManager = manager;
    mHwType = hw_type;
    mBufferQueue = queue;

    mTestCount = 0;
}

ReaderThread::~ReaderThread() {

}

int ReaderThread::openDevice() {

    if (mHwType == McuRPCManager::RPC_SPI) {
        mFd = open("/dev/spi1_0_0", O_RDWR /* | O_NONBLOCK */);
        if ( mFd < 0) {
            ALOGE("%s, open SPI failed \n", __func__);
        }
    } else if (mHwType == McuRPCManager::RPC_UART) {
        // open uart and set baudrate here
    }

    return mFd;
}

int ReaderThread::recvMsg(McuRPCBuffer* buf) {
    // testing code , should be removed 
    mTestCount ++;
    if (mTestCount > 1024)
        mTestCount = 0;
    buf -> setSize(mTestCount);
    // testing code end

    ALOGE("%s, buf size %d\n", __func__, buf->getSize());

    //TODO read data to buf->Data()
    
    return buf -> getSize();

}

void ReaderThread::start() {
    openDevice();
    this -> run("ReaderThread", PRIORITY_HIGHEST);
}

void ReaderThread::stop() {
    requestExitAndWait();
}

bool ReaderThread::threadLoop() {
    McuRPCBuffer* buf = mBufferQueue -> dequeueProducerBuffer();

    recvMsg(buf);

    mBufferQueue -> enqueueConsumerBuffer(buf);

    mManager -> notifyDataReady(mHwType);

    // should remove sleep
    sleep(5); 

    return true;
}

} //namespace
